package cn.rtplay.esp32camcar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;

import java.util.List;
import java.util.Objects;

import cn.rtplay.esp32camcar.databinding.ActivityMainBinding;
import cn.rtplay.esp32camcar.myView.BackDialog;
import cn.rtplay.esp32camcar.toolUtils.AppVersions;
import cn.rtplay.esp32camcar.toolUtils.LogUtil;
import cn.rtplay.esp32camcar.toolUtils.NetworkUtils;
import cn.rtplay.esp32camcar.toolUtils.Tools;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    public static final String EXTRAS_CAR_NO = "CAR_NO";
    public static final String EXTRAS_WIFI_ADDRESS = "CAR_WIFI_ADDRESS";
    private ActivityMainBinding mViewBinding;
    private Context mContext;

    private LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;
    private String mCarNO;
    private String mCarAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mViewBinding.getRoot());
        mContext = this;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        final Intent intent = getIntent();
        mCarNO = intent.getStringExtra(EXTRAS_CAR_NO);
        mCarAddress = intent.getStringExtra(EXTRAS_WIFI_ADDRESS);
        LogUtil.d(TAG, "mCarNO:" + mCarNO + "mCarAddress:" + mCarAddress);

        mViewBinding.munButton.setVisibility(View.GONE);
        mViewBinding.checkIn.setVisibility(View.GONE);
        mViewBinding.checkInText.setVisibility(View.GONE);

//            mViewBinding.munButton.setOnClickListener(view -> {
//            Intent intentScanActivity = new Intent(MainActivity.this, ScanActivity.class);
//            startActivity(intentScanActivity);
//            overridePendingTransition(R.anim.push_up_in, 0);
//            mViewBinding.munButton.setVisibility(View.INVISIBLE);
//            mViewBinding.checkIn.setVisibility(View.INVISIBLE);
//            mViewBinding.checkInText.setVisibility(View.INVISIBLE);
//        });
        mViewBinding.checkIn.setOnClickListener(view -> {
            LogUtil.v(TAG, "onCheckInClicked in "+NetworkUtils.getWifiSSID(mContext) + mCarAddress +mViewBinding.munButton.getText().length());
            if (mViewBinding.munButton.getText().length() != 0) {
                if (NetworkUtils.getWifiSSID(mContext).equals(mCarAddress)) {
                    Intent intentOperationActivity = new Intent(MainActivity.this, OperationActivity.class);
                    intentOperationActivity.putExtra(OperationActivity.EXTRAS_DEV_ADDRESS, mCarAddress);
                    intentOperationActivity.putExtra(OperationActivity.EXTRAS_CAR_NO, mViewBinding.munButton.getText());
                    startActivity(intentOperationActivity);
//                    onBackPressed();
                    finish();
                } else {
                    int ret = NetworkUtils.connectWifiApByNameAndPwd(this, mCarAddress, mCarAddress.substring(6), connectResult -> {
                        if (connectResult) { // wifi连接成功
//                            Intent intentOperationActivity = new Intent(MainActivity.this, OperationActivity.class);
//                            intentOperationActivity.putExtra(OperationActivity.EXTRAS_DEV_ADDRESS, mCarAddress);
//                            intentOperationActivity.putExtra(OperationActivity.EXTRAS_CAR_NO, mViewBinding.munButton.getText());
//                            startActivity(intentOperationActivity);
//                            finish();
                        } else {
                            Toast.makeText(mContext, R.string.conn_error, Toast.LENGTH_LONG).show();
                        }
                    });
                    LogUtil.d(TAG, "connectWifiApByNameAndPwd:" + ret);
                }
            } else {
                Toast.makeText(mContext, R.string.select_car, Toast.LENGTH_LONG).show();
            }
        });

        if (mCarNO == null) {
            mViewBinding.munButton.setVisibility(View.GONE);
            mViewBinding.checkIn.setVisibility(View.GONE);
            mViewBinding.checkInText.setVisibility(View.GONE);
            // 检查设备是否支持 wifi
            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI)) {
                new MaterialDialog.Builder(this)
                        .title(getResources().getString(R.string.prompt))
                        .content(getResources().getString(R.string.not_support_WIFI))
                        .icon(Objects.requireNonNull(ContextCompat.getDrawable(this, R.mipmap.ic_launcher)))
                        .canceledOnTouchOutside(false)
                        .positiveText(getResources().getString(R.string.quit))
                        .onPositive((dialog, which) -> Tools.exitApp(this))
                        .show();
                return;
            }

            StaticLoad staticLoad = new StaticLoad();
            staticLoad.setStaticLoadOnFinishListenerListener(() -> {
                LogUtil.v(TAG, "onProcessFinish: in");
                if (!AppVersions.getInstance().getLocalLoadName(mContext).equals("")) {
                    VideoLoad videoLoad = new VideoLoad();
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.fragment_main, videoLoad, "VID");
                    fragmentTransaction.commit();
//                    Intent intentScanActivity = new Intent(MainActivity.this, ScanActivity.class);
//                    startActivity(intentScanActivity);
//                    overridePendingTransition(R.anim.push_up_in, 0);
                    deviceWifiConnection();
                }
            });
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.fragment_main, staticLoad, "STA");
            fragmentTransaction.commit();
        } else {
            VideoLoad videoLoad = new VideoLoad();
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.fragment_main, videoLoad, "VID");
            fragmentTransaction.commit();
            mViewBinding.munButton.setText(mCarNO);
            mViewBinding.munButton.setVisibility(View.VISIBLE);
            mViewBinding.checkIn.setVisibility(View.VISIBLE);
            mViewBinding.checkInText.setVisibility(View.VISIBLE);
        }

        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ScanActivity.BROADCAST_SHOW_BUTTON);
        intentFilter.addAction(ScanActivity.BROADCAST_SET_CAR_NO);
        localReceiver = new LocalReceiver();
        //注册本地接收器
        localBroadcastManager.registerReceiver(localReceiver, intentFilter);

        AppVersions appVersions = AppVersions.getInstance();
        mViewBinding.appVersion.setText(String.format(getResources().getString(R.string.main_page_version), appVersions.getVersionName(this)));
    }

    @Override
    protected void onDestroy() {
        localBroadcastManager.unregisterReceiver(localReceiver);
        super.onDestroy();
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 1000) {
                exitTime = System.currentTimeMillis();
            } else {
                new BackDialog(this).Builder()
                        .setOnConfirmClickListener(Tools::exitApp)
                        .setOnCancelClickListener(c -> LogUtil.v(TAG, "onClick: Cancel in"))
                        .setCancelText(getString(R.string.cancel))
                        .setConfirmText(getString(R.string.quit))
                        .setTitleText(getString(R.string.dialog_title_edit));
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtil.v(TAG, "onReceive:" + intent.getAction());
            switch (Objects.requireNonNull(intent.getAction())) {
                case ScanActivity.BROADCAST_SHOW_BUTTON: {
                    mViewBinding.munButton.setVisibility(View.VISIBLE);
                    mViewBinding.checkIn.setVisibility(View.VISIBLE);
                    mViewBinding.checkInText.setVisibility(View.VISIBLE);
                    break;
                }
                case ScanActivity.BROADCAST_SET_CAR_NO: {
                    mViewBinding.munButton.setText(Objects.requireNonNull(intent.getExtras()).getString(ScanActivity.BROADCAST_DATA_NUMBER));
                    mCarAddress = Objects.requireNonNull(intent.getExtras()).getString(ScanActivity.BROADCAST_DATA_ADDRESS);
                    break;
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        for (Fragment fragment : fragments) {
            if (fragment != null) {
                fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }

    /* ssid 格式
     * rtcar-redferg-142857
     * rtcar-[3字符颜色描述][3字符品牌描述][1字符型号描述]-[6字符车牌号描述]
     * 详细描述说明见conf格式说明。
     */
    private void deviceWifiConnection() {
        String ssid = NetworkUtils.getWifiSSID(mContext);
        if (Tools.getKeyStringCount(ssid, "-") >= 2) {
            if (ssid.indexOf("rtcar") == 0) {
                mCarAddress = ssid;
                mCarNO = ssid.substring(14);
                mViewBinding.munButton.setText(mCarNO);
                mViewBinding.munButton.setVisibility(View.VISIBLE);
                mViewBinding.checkIn.setVisibility(View.VISIBLE);
                mViewBinding.checkInText.setVisibility(View.VISIBLE);
                return;
            }
        }

        new MaterialDialog.Builder(this)
                .title(getResources().getString(R.string.prompt))
                .content(getResources().getString(R.string.device_wifi_error))
                .icon(Objects.requireNonNull(ContextCompat.getDrawable(this, R.mipmap.ic_launcher)))
                .canceledOnTouchOutside(false)
                .positiveText(getResources().getString(R.string.quit))
                .onPositive((dialog, which) -> Tools.exitApp(this))
                .show();
    }
}